

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/bear.jpg">
  <link rel="icon" href="/img/bear.jpg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Wahoyu">
  <meta name="keywords" content="">
  
    <meta name="description" content="采用自定义注解+AOP切面编程技术，实现快捷高效的日志记录。">
<meta property="og:type" content="article">
<meta property="og:title" content="日志进化：AOP+自定义注解实现日志输出">
<meta property="og:url" content="http://example.com/2022/08/30/%E6%97%A5%E5%BF%97%E8%BF%9B%E5%8C%96%EF%BC%9AAOP+%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3%E5%AE%9E%E7%8E%B0%E6%97%A5%E5%BF%97%E8%BE%93%E5%87%BA/index.html">
<meta property="og:site_name" content="哆啦是个梦-A Coding Bear">
<meta property="og:description" content="采用自定义注解+AOP切面编程技术，实现快捷高效的日志记录。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/image/22.08.30/1.jpg">
<meta property="article:published_time" content="2022-08-30T04:30:30.000Z">
<meta property="article:modified_time" content="2022-08-30T02:12:23.406Z">
<meta property="article:author" content="Wahoyu">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="Spring">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/image/22.08.30/1.jpg">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>日志进化：AOP+自定义注解实现日志输出 - 哆啦是个梦-A Coding Bear</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/shubiao.css#.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.0","typing":{"enable":true,"typeSpeed":90,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":3},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>

  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 30vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>哆啦是个梦</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="日志进化：AOP+自定义注解实现日志输出"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        Wahoyu
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-08-30 12:30" pubdate>
          2022年8月30日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          39 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar category-bar" style="margin-right: -1rem">
    





<div class="category-list">
  
  
    
    
    
    <div class="category row nomargin-x">
      <a class="category-item 
          list-group-item category-item-action col-10 col-md-11 col-xm-11" title="开发"
        id="heading-3ff3c3e26a68112c11c3e80f2a26896e" role="tab" data-toggle="collapse" href="#collapse-3ff3c3e26a68112c11c3e80f2a26896e"
        aria-expanded="true"
      >
        开发
        <span class="list-group-count">(9)</span>
        <i class="iconfont icon-arrowright"></i>
      </a>
      
      <div class="category-collapse collapse show" id="collapse-3ff3c3e26a68112c11c3e80f2a26896e"
           role="tabpanel" aria-labelledby="heading-3ff3c3e26a68112c11c3e80f2a26896e">
        
        
          
  <div class="category-post-list">
    
    
      
      
        <a href="/2022/06/05/SQL%E5%9F%BA%E7%A1%80%E8%AF%AD%E5%8F%A5%E6%97%A5%E5%B8%B8%E7%BB%83%E4%B9%A0/" title="SQL语句练习"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">SQL语句练习</span>
        </a>
      
    
      
      
        <a href="/2022/06/19/%E5%85%B3%E4%BA%8E%E5%8F%8D%E5%B0%84%E4%B8%8E%E6%B3%A8%E8%A7%A3%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E6%80%BB%E7%BB%93/" title="关于反射与注解的理解与总结"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">关于反射与注解的理解与总结</span>
        </a>
      
    
      
      
        <a href="/2022/07/06/JavaWeb/" title="基于Java Web的图书管理系统"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">基于Java Web的图书管理系统</span>
        </a>
      
    
      
      
        <a href="/2022/06/27/%E5%9F%BA%E4%BA%8EMybatis-JUL-Lombok-Maven%E7%9A%84%E5%9B%BE%E4%B9%A6%E7%AE%A1%E7%90%86%E7%B3%BB%E7%BB%9F%EF%BC%88%E5%B8%A6%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95%EF%BC%89/" title="基于Mybatis的图书管理系统"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">基于Mybatis的图书管理系统</span>
        </a>
      
    
      
      
        <a href="/2022/07/26/BookManagerSSM/" title="基于SSM+Security的图书管理系统"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">基于SSM+Security的图书管理系统</span>
        </a>
      
    
      
      
        <a href="/2022/06/10/%E7%AE%80%E5%8D%95%E7%AE%97%E6%B3%95%EF%BC%88Java%E5%AE%9E%E7%8E%B0%EF%BC%89/" title="排序与搜索算法（Java实现）"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">排序与搜索算法（Java实现）</span>
        </a>
      
    
      
      
        <a href="/2022/06/08/Java%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%AE%80%E5%8D%95%E5%AE%9E%E7%8E%B0/" title="数据结构实现（Java）"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">数据结构实现（Java）</span>
        </a>
      
    
      
      
        <a href="/2022/08/30/%E6%97%A5%E5%BF%97%E8%BF%9B%E5%8C%96%EF%BC%9AAOP+%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3%E5%AE%9E%E7%8E%B0%E6%97%A5%E5%BF%97%E8%BE%93%E5%87%BA/" title="日志进化：AOP+自定义注解实现日志输出"
           class="list-group-item list-group-item-action
           active">
          <span class="category-post">日志进化：AOP+自定义注解实现日志输出</span>
        </a>
      
    
      
      
        <a href="/2022/06/03/%E8%A7%A3%E5%86%B3Linux%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F%E6%AF%8F%E6%AC%A1%E8%A6%81source-etc-profile%E9%97%AE%E9%A2%98/" title="解决Linux环境变量每次要source /etc/profile问题"
           class="list-group-item list-group-item-action
           ">
          <span class="category-post">解决Linux环境变量每次要source /etc/profile问题</span>
        </a>
      
    
  </div>

        
      </div>
    </div>
  
</div>


  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">日志进化：AOP+自定义注解实现日志输出</h1>
            
            <div class="markdown-body">
              
              <p>采用自定义注解+AOP切面编程技术，实现快捷高效的日志记录。</p>
<span id="more"></span>

<p>在项目进行中我们在日志记录的过程中，发现一种日志记录方式为 AOP+自定义注解+工具类的实现方式。</p>
<p>这到底是什么原理？这种方式究竟有什么用途？</p>
<h2 id="1、传统的日志用法"><a href="#1、传统的日志用法" class="headerlink" title="1、传统的日志用法"></a>1、传统的日志用法</h2><h3 id="1-1、实现展示"><a href="#1-1、实现展示" class="headerlink" title="1.1、实现展示"></a>1.1、实现展示</h3><p>我们来看看传统的日志用法，我们将日志记录的行为放在Service方法的逻辑中，通过调用LogUtils工具类中的方法（LogUtils工具类代码省略），对日志进行输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">findArticleById</span><span class="hljs-params">(Long articleId)</span> &#123;<br>    <span class="hljs-comment">//业务代码省略...</span><br>    LogUtils.addLog(<span class="hljs-string">&quot;文章&quot;</span> , <span class="hljs-string">&quot;获取文章列表&quot;</span>);<br>    <span class="hljs-keyword">return</span> Result.success(articleVo);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="1-2、存在问题"><a href="#1-2、存在问题" class="headerlink" title="1.2、存在问题"></a>1.2、存在问题</h3><p>这个方式还是有一定的问题：</p>
<p>日志记录代码与业务代码强耦合：我们此时在<code>LogUtils.addLog()</code>方法中定义了两个参数，可如果有一天我们想在这个方法中再加入一个参数，那么我们就要修改底层工具类+所有调用的地方进行修改，这是因为方法的调用不能缺少参数。</p>
<h2 id="2、进化后的日志用法"><a href="#2、进化后的日志用法" class="headerlink" title="2、进化后的日志用法"></a>2、进化后的日志用法</h2><h3 id="2-1、实现展示"><a href="#2-1、实现展示" class="headerlink" title="2.1、实现展示"></a>2.1、实现展示</h3><p>我们采用  自定义注解+AOP切面编程技术，实现日志记录，现在记录日志的方式就是这样了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-meta">@LogAnnotation(module = &quot;文章&quot;,operation = &quot;获取文章列表&quot;)</span><br><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> Result <span class="hljs-title function_">findArticleById</span><span class="hljs-params">(Long articleId)</span> &#123;<br>    <span class="hljs-comment">//业务代码省略...</span><br>    <span class="hljs-keyword">return</span> Result.success(articleVo);<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="2-2、此方法的优点"><a href="#2-2、此方法的优点" class="headerlink" title="2.2、此方法的优点"></a>2.2、此方法的优点</h3><ul>
<li>使用注解于方法上面很方便</li>
<li>对于参数的添加和修改很方便（可以直接在自定义注解中进行参数修改）</li>
<li>在我们添加了参数之后，我们不用修改注解的调用（因为我们在注解的定义添加了默认值）</li>
</ul>
<h2 id="3、代码实现"><a href="#3、代码实现" class="headerlink" title="3、代码实现"></a>3、代码实现</h2><p>我们定义一个注解加载业务代码方法上，使用AOP查找注解的调用，并对其方法进行逻辑增强</p>
<h3 id="3-1、自定义注解"><a href="#3-1、自定义注解" class="headerlink" title="3.1、自定义注解"></a>3.1、自定义注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 自定义注解+AOP实现日志记录</span><br><span class="hljs-comment"> * 自定义注解：使用元注解定义注解</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Wahoyu</span><br><span class="hljs-comment"> */</span><br><br><span class="hljs-meta">@Target(ElementType.METHOD)</span>  <span class="hljs-comment">//该注解可放在方法上面</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span>  <span class="hljs-comment">//运行时注解</span><br><span class="hljs-meta">@Documented</span>    <span class="hljs-comment">//可生成文档</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> LogAnnotation &#123;<br><br>    String <span class="hljs-title function_">module</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">&quot;&quot;</span>;   <span class="hljs-comment">//定义了注解的参数、参数的默认值</span><br>    String <span class="hljs-title function_">operation</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> <span class="hljs-string">&quot;&quot;</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-2、AOP工具类"><a href="#3-2、AOP工具类" class="headerlink" title="3.2、AOP工具类"></a>3.2、AOP工具类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * 自定义注解+AOP实现日志记录</span><br><span class="hljs-comment"> * AOP工具类</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@Aspect</span><br><span class="hljs-meta">@Component</span><br><span class="hljs-meta">@Slf4j</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">LogAspect</span> &#123;<br><br>    <span class="hljs-comment">//插入位置：使用此注解的方法</span><br>    <span class="hljs-meta">@Pointcut(&quot;@annotation(com.blog.common.aop.LogAnnotation)&quot;)</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">logPointCut</span><span class="hljs-params">()</span> &#123;<br>    &#125;<br><br>    <span class="hljs-comment">//插入形式：上下包围</span><br>    <span class="hljs-meta">@Around(&quot;logPointCut()&quot;)</span><br>    <span class="hljs-keyword">public</span> Object <span class="hljs-title function_">around</span><span class="hljs-params">(ProceedingJoinPoint point)</span> <span class="hljs-keyword">throws</span> Throwable &#123;<br>        <span class="hljs-type">long</span> <span class="hljs-variable">beginTime</span> <span class="hljs-operator">=</span> System.currentTimeMillis();<br>        <span class="hljs-comment">//执行方法</span><br>        <span class="hljs-type">Object</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> point.proceed();<br>        <span class="hljs-comment">//执行时长(毫秒)</span><br>        <span class="hljs-type">long</span> <span class="hljs-variable">time</span> <span class="hljs-operator">=</span> System.currentTimeMillis() - beginTime;<br>        <span class="hljs-comment">//输出日志</span><br>        recordLog(point, time);<br>        <span class="hljs-keyword">return</span> result;<br>    &#125;<br><br>    <span class="hljs-comment">//输出日志方法</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">recordLog</span><span class="hljs-params">(ProceedingJoinPoint joinPoint, <span class="hljs-type">long</span> time)</span> &#123;<br>        <span class="hljs-type">MethodSignature</span> <span class="hljs-variable">signature</span> <span class="hljs-operator">=</span> (MethodSignature) joinPoint.getSignature();<br>        <span class="hljs-type">Method</span> <span class="hljs-variable">method</span> <span class="hljs-operator">=</span> signature.getMethod();<br>        <span class="hljs-type">LogAnnotation</span> <span class="hljs-variable">logAnnotation</span> <span class="hljs-operator">=</span> method.getAnnotation(LogAnnotation.class);<br>        log.info(<span class="hljs-string">&quot;=====================log start================================&quot;</span>);<br>        log.info(<span class="hljs-string">&quot;module:&#123;&#125;&quot;</span>,logAnnotation.<span class="hljs-keyword">module</span>());<br>        log.info(<span class="hljs-string">&quot;operation:&#123;&#125;&quot;</span>,logAnnotation.operation());<br><br>        <span class="hljs-comment">//请求的方法名</span><br>        <span class="hljs-type">String</span> <span class="hljs-variable">className</span> <span class="hljs-operator">=</span> joinPoint.getTarget().getClass().getName();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">methodName</span> <span class="hljs-operator">=</span> signature.getName();<br>        log.info(<span class="hljs-string">&quot;request method:&#123;&#125;&quot;</span>,className + <span class="hljs-string">&quot;.&quot;</span> + methodName + <span class="hljs-string">&quot;()&quot;</span>);<br><br>        <span class="hljs-comment">//请求的参数</span><br>        Object[] args = joinPoint.getArgs();<br>        <span class="hljs-type">String</span> <span class="hljs-variable">params</span> <span class="hljs-operator">=</span> JSON.toJSONString(args[<span class="hljs-number">0</span>]);<br>        log.info(<span class="hljs-string">&quot;params:&#123;&#125;&quot;</span>,params);<br><br>        <span class="hljs-comment">//获取request 设置IP地址</span><br>        <span class="hljs-type">HttpServletRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> HttpContextUtils.getHttpServletRequest();<br>        log.info(<span class="hljs-string">&quot;ip:&#123;&#125;&quot;</span>, IpUtils.getIpAddr(request));<br><br>        <span class="hljs-comment">//执行时间</span><br>        log.info(<span class="hljs-string">&quot;excute time : &#123;&#125; ms&quot;</span>,time);<br>        log.info(<span class="hljs-string">&quot;=====================log end================================&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-3、Http工具类"><a href="#3-3、Http工具类" class="headerlink" title="3.3、Http工具类"></a>3.3、Http工具类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Http工具类，用于获取Ip地址</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Wahoyu</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">HttpContextUtils</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> HttpServletRequest <span class="hljs-title function_">getHttpServletRequest</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="3-4、IpUtils工具类"><a href="#3-4、IpUtils工具类" class="headerlink" title="3.4、IpUtils工具类"></a>3.4、IpUtils工具类</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs Java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * IpUtils工具类，用于获取Ip地址</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> Wahoyu</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">IpUtils</span> &#123;<br><br>  <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-type">Logger</span> <span class="hljs-variable">logger</span> <span class="hljs-operator">=</span> LoggerFactory.getLogger(IpUtils.class);<br><br>  <span class="hljs-comment">/**</span><br><span class="hljs-comment">   * 获取IP地址</span><br><span class="hljs-comment">   * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址</span><br><span class="hljs-comment">   * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址</span><br><span class="hljs-comment">   */</span><br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">getIpAddr</span><span class="hljs-params">(HttpServletRequest request)</span> &#123;<br>    <span class="hljs-type">String</span> <span class="hljs-variable">ip</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>    <span class="hljs-keyword">try</span> &#123;<br>      ip = request.getHeader(<span class="hljs-string">&quot;x-forwarded-for&quot;</span>);<br>      <span class="hljs-keyword">if</span> (StringUtils.isEmpty(ip) || <span class="hljs-string">&quot;unknown&quot;</span>.equalsIgnoreCase(ip)) &#123;<br>        ip = request.getHeader(<span class="hljs-string">&quot;Proxy-Client-IP&quot;</span>);<br>      &#125;<br>      <span class="hljs-keyword">if</span> (StringUtils.isEmpty(ip) || ip.length() == <span class="hljs-number">0</span> || <span class="hljs-string">&quot;unknown&quot;</span>.equalsIgnoreCase(ip)) &#123;<br>        ip = request.getHeader(<span class="hljs-string">&quot;WL-Proxy-Client-IP&quot;</span>);<br>      &#125;<br>      <span class="hljs-keyword">if</span> (StringUtils.isEmpty(ip) || <span class="hljs-string">&quot;unknown&quot;</span>.equalsIgnoreCase(ip)) &#123;<br>        ip = request.getHeader(<span class="hljs-string">&quot;HTTP_CLIENT_IP&quot;</span>);<br>      &#125;<br>      <span class="hljs-keyword">if</span> (StringUtils.isEmpty(ip) || <span class="hljs-string">&quot;unknown&quot;</span>.equalsIgnoreCase(ip)) &#123;<br>        ip = request.getHeader(<span class="hljs-string">&quot;HTTP_X_FORWARDED_FOR&quot;</span>);<br>      &#125;<br>      <span class="hljs-keyword">if</span> (StringUtils.isEmpty(ip) || <span class="hljs-string">&quot;unknown&quot;</span>.equalsIgnoreCase(ip)) &#123;<br>        ip = request.getRemoteAddr();<br>      &#125;<br>    &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>      logger.error(<span class="hljs-string">&quot;IPUtils ERROR &quot;</span>, e);<br>    &#125;<br>    <span class="hljs-comment">// 使用代理，则获取第一个IP地址</span><br>    <span class="hljs-keyword">if</span> (StringUtils.isEmpty(ip) &amp;&amp; ip.length() &gt; <span class="hljs-number">15</span>) &#123;<br>      <span class="hljs-keyword">if</span> (ip.indexOf(<span class="hljs-string">&quot;,&quot;</span>) &gt; <span class="hljs-number">0</span>) &#123;<br>        ip = ip.substring(<span class="hljs-number">0</span>, ip.indexOf(<span class="hljs-string">&quot;,&quot;</span>));<br>      &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> ip;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>至此SpringBoot+AOP+Annotation的日志输出功能实现完成。</p>

              
            </div>
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%BC%80%E5%8F%91/" class="category-chain-item">开发</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Java/">#Java</a>
      
        <a href="/tags/Spring/">#Spring</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>日志进化：AOP+自定义注解实现日志输出</div>
      <div>http://example.com/2022/08/30/日志进化：AOP+自定义注解实现日志输出/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Wahoyu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年8月30日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/07/26/BookManagerSSM/" title="基于SSM+Security的图书管理系统">
                        <span class="hidden-mobile">基于SSM+Security的图书管理系统</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  <article id="comments" lazyload>
    
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.4.16/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"7WuaJQGQGU5GFxMKMtDzWYVI-gzGzoHsz","appKey":"zdCzx5CuURztPQQoi8LuXSWv","path":"window.location.pathname","placeholder":"请留下您的想法...","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":true,"serverURLs":"https://7wuajqgq.lc-cn-n1-shared.com","emojiCDN":null,"emojiMaps":null,"enableQQ":true},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


  </article>


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  






    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <text>哆啦是个梦</text> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数...</span> <span id="times">载入时分秒...</span> <script src="/js/duration.js"></script> </div> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  

  

  

  

  

  

  




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.0/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script>
  (function() {
    var enableLang = CONFIG.code_language.enable && CONFIG.code_language.default;
    var enableCopy = CONFIG.copy_btn;
    if (!enableLang && !enableCopy) {
      return;
    }

    function getBgClass(ele) {
      return Fluid.utils.getBackgroundLightness(ele) >= 0 ? 'code-widget-light' : 'code-widget-dark';
    }

    var copyTmpl = '';
    copyTmpl += '<div class="code-widget">';
    copyTmpl += 'LANG';
    copyTmpl += '</div>';
    jQuery('.markdown-body pre').each(function() {
      var $pre = jQuery(this);
      if ($pre.find('code.mermaid').length > 0) {
        return;
      }
      if ($pre.find('span.line').length > 0) {
        return;
      }

      var lang = '';

      if (enableLang) {
        lang = CONFIG.code_language.default;
        if ($pre[0].children.length > 0 && $pre[0].children[0].classList.length >= 2 && $pre.children().hasClass('hljs')) {
          lang = $pre[0].children[0].classList[1];
        } else if ($pre[0].getAttribute('data-language')) {
          lang = $pre[0].getAttribute('data-language');
        } else if ($pre.parent().hasClass('sourceCode') && $pre[0].children.length > 0 && $pre[0].children[0].classList.length >= 2) {
          lang = $pre[0].children[0].classList[1];
          $pre.parent().addClass('code-wrapper');
        } else if ($pre.parent().hasClass('markdown-body') && $pre[0].classList.length === 0) {
          $pre.wrap('<div class="code-wrapper"></div>');
        }
        lang = lang.toUpperCase().replace('NONE', CONFIG.code_language.default);
      }
      $pre.append(copyTmpl.replace('LANG', lang).replace('code-widget">',
        getBgClass($pre[0]) + (enableCopy ? ' code-widget copy-btn" data-clipboard-snippet><i class="iconfont icon-copy"></i>' : ' code-widget">')));

      if (enableCopy) {
        Fluid.utils.createScript('https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js', function() {
          var clipboard = new window.ClipboardJS('.copy-btn', {
            target: function(trigger) {
              var nodes = trigger.parentNode.childNodes;
              for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].tagName === 'CODE') {
                  return nodes[i];
                }
              }
            }
          });
          clipboard.on('success', function(e) {
            e.clearSelection();
            e.trigger.innerHTML = e.trigger.innerHTML.replace('icon-copy', 'icon-success');
            setTimeout(function() {
              e.trigger.innerHTML = e.trigger.innerHTML.replace('icon-success', 'icon-copy');
            }, 2000);
          });
        });
      }
    });
  })();
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiantiao.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
